package hcb.dms.soDoTuyen;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import hcb.dms.JSONParser;
import hcb.dms.R;
import hcb.dms.R.layout;
import hcb.dms.UserSessionManager;

public class Edit_soDoTuyen extends Activity {

	EditText txTenTuyen, txDienThoai,txGhiChu,txMST;
	Button btSua, btnDelete, btAdd;
	TextView txMaTuyen, txSoLuong;

	String pid;
	String tenTuyen;
	String soLuong;
	JSONObject objX;

	// Progress Dialog
	private ProgressDialog pDialog;

	// JSON parser class
	JSONParser jsonParser = new JSONParser();
	JSONObject product;

	// JSON Node names
	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_KHACHHANG = "khachHang";
	private static final String TAG_MESSAGE = "message";
	private static final String TAG_MAKH = "maKH";
	private static final String TAG_TENKH = "tenKH";
	private static final String TAG_DIACHI = "diaChi";
	private static final String TAG_LIENHE = "lienHe";
	private static final String TAG_DIENTHOAI = "dienThoai";
	private static final String TAG_GPSLAT = "gpsLat";
	private static final String TAG_GPSLONG = "gpsLong";
	private static final String TAG_TENTUYEN ="tenTuyen";
	private static final String TAG_SOLUONG = "soLuong";
	private static final String TAG_MATUYEN = "maTuyen";
	private static final String TAG_ID = "id";

	private static final String TAG_GHICHU = "ghiChu";
	private static final String TAG_MST = "maSoThue";

	// products JSONArray
	JSONArray products = null;
	UserSessionManager session;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(layout.edit_so_do_tuyen);
		session = new UserSessionManager(getApplicationContext());
		// save button
		btSua = (Button) findViewById(R.id.btUpdate);
		btnDelete = (Button) findViewById(R.id.btDelete);
		btAdd = (Button) findViewById(R.id.btAdd);

		txMaTuyen = (TextView) findViewById(R.id.txMaTuyen);
		txTenTuyen = (EditText) findViewById(R.id.txTenTuyen);

		txSoLuong = (TextView) findViewById(R.id.txSoLuong);

		// getting product details from intent
		Intent i = getIntent();

		// getting product id (pid) from intent
		pid = i.getStringExtra(TAG_ID);
		tenTuyen = i.getStringExtra(TAG_TENTUYEN);
		soLuong =  i.getStringExtra(TAG_SOLUONG);

		txMaTuyen.setText(pid);
		txTenTuyen.setText(tenTuyen);
		txSoLuong.setText(soLuong);

		// Getting complete product details in background thread
	//	new GetKhachHangDetails().execute();

		// save button click event
		btSua.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// starting background task to update product
				new UpdateTenSoDoTuyen().execute();
			}
		});

		// Delete button click event
		btnDelete.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// deleting khach hang in background thread
				new DeleteSoDoTuyen().execute();
			}
		});
		btAdd.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// update gps  in background thread
			//	new UpdateGPSKhachHangDetails().execute();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.edit_so_do_tuyen, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	class UpdateTenSoDoTuyen extends AsyncTask<String, String, String> {
		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_soDoTuyen.this);
			pDialog.setMessage("Saving so do tuyen hang ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Saving product
		 */
		protected String doInBackground(String... args) {

			// getting updated data from EditTexts
			txMaTuyen = (TextView) findViewById(R.id.txMaTuyen);
			txTenTuyen = (EditText) findViewById(R.id.txTenTuyen);


			String maTuyen = txMaTuyen.getText().toString();
			String tenTuyen = txTenTuyen.getText().toString();

			String j = "{\"soDoTuyen\":{\""+TAG_MATUYEN+"\":\""+maTuyen+"\",\""+TAG_TENTUYEN+"\":\""+tenTuyen+"\"}}";

			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "UTSDT"));
			params.add(new BasicNameValuePair(TAG_MATUYEN,maTuyen));
			params.add(new BasicNameValuePair(TAG_TENTUYEN,tenTuyen));
			params.add(new BasicNameValuePair(session.TAG_PID,pid));
			params.add(new BasicNameValuePair(session.TAG_OBJ, j));


			// sending modified data through http request
			// Notice that update product url accepts POST method
			JSONObject json = jsonParser.makeHttpRequest(session.URL,"POST", params);

			// check json success tag
			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHACHHANG);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}

			return null;
		}


		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			// dismiss the dialog once product uupdated
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thong bao: " + str.toString(), Toast.LENGTH_LONG);
			}
			finish();
			pDialog.dismiss();
		}
	}
	class DeleteSoDoTuyen extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Edit_soDoTuyen.this);
			pDialog.setMessage("Deleting so do tuyen...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(true);
			pDialog.show();
		}

		/**
		 * Deleting product
		 */
		protected String doInBackground(String... args) {
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(session.KEY_USERNAME, session.getUsername()));
			params.add(new BasicNameValuePair(session.KEY_PASSWORD, session.getPassword()));
			params.add(new BasicNameValuePair(session.TAG_DANGNHAP, "OK"));
			params.add(new BasicNameValuePair(session.TAG_THAOTAC, "DSDT"));
			params.add(new BasicNameValuePair(TAG_MATUYEN, pid));
		//	params.add(new BasicNameValuePair(session.TAG_OBJ, objX.toString()));
			JSONObject json = jsonParser.makeHttpRequest(session.URL, "POST", params);
			// check your log for json response
			// json success tag

			try {
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// send result code 100 to notify about product update
					return json.getString(TAG_KHACHHANG);

				} else {
					String mess = json.getString(TAG_MESSAGE);
					Toast.makeText(getApplicationContext(), mess.toString(), Toast.LENGTH_LONG);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.d("JSON out", json.toString());
			}
			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * *
		 */
		protected void onPostExecute(String str) {
			if(str!="1")
			{
				Toast.makeText(getApplicationContext(), "Thong bao: " + str.toString(), Toast.LENGTH_LONG);
			}
			else
				finish();
			pDialog.dismiss();

		}

	}

}
